#include"head.h"
ListNode* buyNode(LTDataType x)
{
	ListNode* pp = (ListNode*)malloc(sizeof(ListNode));
	if (pp==NULL)
	{
		perror("malloc fail");
		exit(1);
	}
	pp->data = x; 
	pp->next = pp->prev = pp;
	return pp;
}

ListNode* ListCreate()
{
	ListNode* plist = buyNode(-1);
	return plist;
}

void ListDestory(ListNode* pHead)
{
	assert(pHead);
	ListNode* pcur = pHead->next;
	while (pcur != pHead)
	{
		ListNode* pp = pcur;
		pcur = pcur->next;
		free(pp);
	}
	free(pHead);
}

void ListPrint(ListNode* pHead)
{
	assert(pHead);
	ListNode* pcur = pHead->next;
	while (pcur != pHead)
	{
		printf("%d->", pcur->data);
		pcur = pcur->next;
	}
	printf("\n");
}

void ListPushBack(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	ListNode* p = buyNode(x);
	p->prev = pHead->prev;
	p->next = pHead;
	pHead->prev->next = p;
	pHead->prev = p;
}

void ListPopBack(ListNode* pHead)
{
	assert(pHead);
	ListNode* p = pHead->prev;
	pHead->prev = p->prev;
	p->prev->next = pHead;
	free(p);
}

void ListPushFront(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	ListNode* pp = buyNode(x);
	if (pHead->next == NULL) 
	{
		pHead->next = pp;
		pp->prev = pHead;
		pp->next = pHead;
	}
	else
	{
		pp->next = pHead->next;
		pp->prev = pHead;
		pHead->next->prev = pp;
		pHead->next = pp;
	}
}
void ListPopFront(ListNode* pHead)
{
	ListNode* tmp = pHead->next;
	tmp->next->prev = pHead;
	pHead->next = tmp->next;
	free(tmp);
}

ListNode* ListFind(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	ListNode* pcur = pHead->next;
	while (pcur != pHead)
	{
		if (pcur->data = x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}

void ListInsert(ListNode* pos, LTDataType x)
{
	assert(pos);
	ListNode* pp = buyNode(x);
	pp->prev = pos->prev;
	pp->next = pos;
	pos->prev->next = pp;
	pos->prev = pp;
}

void ListErase(ListNode* pos)
{
	assert(pos);
	pos->next->prev = pos->prev;
	pos->prev->next = pos->next;
	free(pos);
}
